import { relationalStore, ValuesBucket } from "@kit.ArkData";
import { common } from "@kit.AbilityKit";
import { promptAction } from "@kit.ArkUI";
import { LogDomain, LogHelper } from "../utils/LogHelper";

const TAG: string = 'KitDemo-PUSH-RDB';
const logHelper: LogHelper = LogHelper.getLogHelper(LogDomain.DEBUG_MAIN, TAG);

interface DataType {
  data: string
}

export interface pushBucket {
  id: number,
  message: string,
  push_type: string,
  message_id: string
}

//创建数据库及相关表
export class RdbUtils {
  rdbStore?: relationalStore.RdbStore;
  context: common.UIAbilityContext | undefined = AppStorage.get('AbilityContext');

  public async getOrCreatStore() {
    logHelper.showInfo('getOrCreatStore start');
    // 数据库配置
    const STORE_CONFIG: relationalStore.StoreConfig = {
      name: 'pushMessage.db',
      securityLevel: relationalStore.SecurityLevel.S3,
      customDir: 'pushmessage/t_push_message',
    };
    // 获取数据库Store
    if (this.context !== undefined) {
      const rdbStore = await relationalStore.getRdbStore(this.context, STORE_CONFIG);
      logHelper.showInfo(`push rdb store.version:${rdbStore.version}`);
      logHelper.showInfo(`push rdb store.rebuilt:${rdbStore.rebuilt}`);
      if (rdbStore.version === 0) {
        //建表语句
        const SQL_CREATE_TABLE =
          'CREATE TABLE IF NOT EXISTS t_push_message (id INTEGER PRIMARY KEY AUTOINCREMENT,message_id TEXT NOT NULL,push_type TEXT NOT NULL,message_action INTEGER,message TEXT NOT NULL,field1 TEXT NOT NULL,field2 TEXT NOT NULL,field3 TEXT NOT NULL,field4 TEXT NOT NULL,field5 TEXT NOT NULL,create_time INTEGER)';
        rdbStore.executeSql(SQL_CREATE_TABLE);
        rdbStore.version = 1;
        logHelper.showInfo('executeSql RdbStore Succeeded.');
      }
      return rdbStore
    } else {
      logHelper.showError('context is null');
      return;
    }
  }

  public async InsertData(message_id: string, push_type: string, message: string) {
    // 插入数据
    const valueBucket: ValuesBucket = {
      'message_id': message_id,
      'push_type': push_type,
      'message': message
    };
    let rdbStore = await this.getOrCreatStore();
    if (rdbStore !== undefined) {
      rdbStore.insert('t_push_message', valueBucket, (err, rowId) => {
        if (err) {
          logHelper.showError(`Failed to insert data. Code:${err.code}, message:${err.message}`);
          return;
        }
        logHelper.showError(`Succeeded in inserting data. rowId:${rowId}`);
      })
    } else {
      logHelper.showError(`Failed to insert data, rdb is undefined`);
    }
  }

  public async QueryData(): Promise<pushBucket[]> {
    logHelper.showError(`QueryData start`);
    // 配置谓词
    let predicates = new relationalStore.RdbPredicates("t_push_message");
    predicates.orderByDesc('id');
    let rdbStore = await this.getOrCreatStore();
    let jsonData: Array<pushBucket> = new Array<pushBucket>();
    if (rdbStore !== undefined) {
      rdbStore.query(predicates, (err, resultSet) => {
        if (err) {
          logHelper.showError(`Failed to query data. Code:${err.code}, message:${err.message}`);
          return;
        }
        logHelper.showError(`query result column names: ${resultSet.columnNames}, row count: ${resultSet.rowCount}`);
        // resultSet是一个数据集合的游标，默认指向第-1个记录，有效的数据从0开始。
        let showBackgroundMessage = '';
        while (resultSet.goToNextRow()) {
          const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
          const message_id = resultSet.getString(resultSet.getColumnIndex("message_id"));
          const push_type = resultSet.getString(resultSet.getColumnIndex("push_type"));
          const message = resultSet.getString(resultSet.getColumnIndex("message"));
          let afterMessage: DataType = JSON.parse(message);
          const valueItem: pushBucket = {
            id: id,
            message_id: message_id,
            push_type: push_type,
            message: afterMessage.data
          };
          jsonData.push(valueItem);
          showBackgroundMessage +=
          `id=${id}, message_id=${message_id}, push_type=${push_type}, message=${afterMessage.data}` +
            '\n';
          console.log(showBackgroundMessage);
        }
        promptAction.showToast({
          message: '后台缓存消息(数据库):' + "\n" +
            showBackgroundMessage,
          duration: 10000,
          bottom: 200
        });
        // 释放数据集的内存
        resultSet.close();
      })
    }

    return jsonData;
  }
}